package org.gitos.cloud.cmd.interceptor;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.gitos.cloud.domain.annotation.UnAuth;
import org.gitos.cloud.util.RedisHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

/**
 * Created by shizhengchu on 16/4/10.
 */
@Aspect
@Component
public class AuthInterceptor {

    private static final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

    @Around("execution(* org.gitos.cloud.cmd.controller..*Controller.*(..))")
    public Object auth(ProceedingJoinPoint joinPoint) throws Throwable {
        if (joinPoint.getSignature().getDeclaringType().isAnnotationPresent(UnAuth.class)) {
            return joinPoint.proceed();
        }
        if (((MethodSignature) joinPoint.getSignature()).getMethod().isAnnotationPresent(UnAuth.class)) {
            return joinPoint.proceed();
        }

        Object[] params = joinPoint.getArgs();
        HttpServletRequest request = null;
        for (Object param : params) {
            if (param instanceof HttpServletRequest) {
                request = (HttpServletRequest) param;
                break;
            }
        }
        if (request == null) {
            throw new RuntimeException("no request param");
        }
        String uuid = request.getParameter("auth_uuid");
        Object user = RedisHelper.get(uuid);
        if (user == null) {
            throw new RuntimeException("unAuth");
        }
        request.setAttribute("userId", uuid);
        RedisHelper.set(uuid, JSONObject.toJSONString(user), 36, TimeUnit.DAYS);
        return joinPoint.proceed();
    }


}
